import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';

import 'log.dart';

class XCache {
  SharedPreferences? prefs;

  XCache._() {
    init();
  }

  static XCache? _instance;

  //预初始化，防止使用get时，prefs还未完成初始化,在页面init前调用一次
  static Future<XCache?> preInit() async {
    if (_instance == null) {
      var prefs = await SharedPreferences.getInstance();
      _instance = XCache._pre(prefs);
    }
    return _instance;
  }

  static XCache getInstance() {
    _instance ??= XCache._();
    return _instance!;
  }

  void init() async {
    prefs ??= await SharedPreferences.getInstance();
  }

  XCache._pre(SharedPreferences this.prefs);

  setString(String key, String value) {
    prefs!.setString(key, value);
  }

  setBool(String key, bool value) {
    prefs!.setBool(key, value);
  }

  setInt(String key, int value) {
    prefs!.setInt(key, value);
  }

  setDouble(String key, double value) {
    prefs!.setDouble(key, value);
  }

  setStringList(String key, List<String> value) {
    prefs!.setStringList(key, value);
  }

  deleteKey(String key) {
    prefs!.remove(key);
  }

  deleteAll() {
    prefs!.clear();
  }

  T? get<T>(String key) {
    var result = prefs?.get(key);
    if (result != null) {
      return result as T;
    }
    return null;
  }

  /// 保存模型对象
  Future<void> saveModel<T>(String key, T model) async {
    final jsonString = json.encode(model);
    final result = await prefs?.setString(key, jsonString);
    Log.d('数据保存：${result == true ? '成功' : '失败'}');
  }

  /// 获取模型对象
  Future<T?> getModel<T>(
      String key, T Function(Map<String, dynamic>) fromJson) async {
    final jsonString = prefs?.getString(key);
    if (jsonString == null) {
      return null;
    }
    final jsonMap = json.decode(jsonString);
    return fromJson(jsonMap);
  }
}
